/**
 * @author:linjiye
 * @date: 2025/1/7
 * @desc:
 **/

import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useCallback, useEffect, useState} from 'react'
import FormTitle from "@/components/FormTitle";
import FcSlider from "@/components/FcSlider";
import FcBtnScrollTab from "@/components/FcBtnScrollTab";
import {useLocalSearchParams, useRouter} from "expo-router";
import FcFileItem from "@/components/FcFileItem";
import {Flex, Toast} from "@ant-design/react-native";
import {useDispatch, useSelector} from "react-redux";
import {set_pageRouterParams, set_selectFileList, setSelectFileData} from "@/store/reducer/aiFeeding/aiFeedingSlice"
import FcModal from "@/components/FcModal";
import FcButton from "@/components/FcButton";
import FcTextInput from "@/components/FcTextInput";
import {
    useAddLibraryMutation,
    useDeleteFileMutation,
    useGetDocPartsMutation, useGetMaxFilesQuery, useGetProductUsageQuery,
    useLabelListQuery, useLibraryAiMutation,
    useLibraryListQuery, useSaveKeywordMutation
} from "@/store/api/aiFeeding/aiFeedingApi";
import FileTabBtn from "@/components/FileTabBtn";
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import {useOssAccessInfoQuery} from "@/store/api/oss/ossApi";
import {Video} from "expo-av";

type Props = {}

const fileFeed = (props: Props) => {
    const {id} = useLocalSearchParams()
    const router = useRouter();
    const dispatch = useDispatch();
    let p = useSelector(state => state.aiFeeding.pageRouterParams)
    const [capacity, setCapacity] = useState(50)
    const [showDetail,setShowDetail] = useState(false)
    const [detail,setDetail] = useState({
        url: 'https://img1.baidu.com/it/u=2217154527,684770200&fm=253&fmt=auto&app=138&f=JPEG?w=607&h=422',
        tap: '',
        id: 1,
        type: 'video',
        isSelected: false
    })
    const [isDelete, setIsDelete] = useState(false)
    const [labelList,setLabelList] = useState([])
    const [labelIndex,setLabelIndex] = useState(0)
    const [libraryList,setLibraryList] = useState([])

    const [libraryParams,setLibraryParams] = useState({
        fileName: '',
        fileSourceType: 1,
        thirdPartyId: id,
        pageNo: 1,
        pageSize: 20,
    })
    const [selectFile,setSelectFile] = useState([])
    const [detailList,setDetailList] = useState([])
    const [detailIndex,setDetailIndex] = useState(0)

    const [fileUrl,setFileUrl] = useState('')
    
    const [labelItem,setLabelItem] = useState({})
    const [maxFiles,setMaxFiles] = useState('')


    // const selectFileListSlice = useSelector(state => state.aiFeeding.selectFileList)

    const {data:labelData,isSuccess:labelSuccess,refetch:labelRefetch} = useLabelListQuery({
        name: '',
        pageSize: 1000
    })
    const {data:libraryData,isSuccess:librarySuccess,refetch:libraryRefetch} = useLibraryListQuery(libraryParams)
    const [deleteFileFun] = useDeleteFileMutation()
    const [getDocPartsFun] = useGetDocPartsMutation()
    const [libraryAiFun] = useLibraryAiMutation()
    const [saveKeywordFun] = useSaveKeywordMutation()
    const {data:ossInfo,refetch:ossRefetch} = useOssAccessInfoQuery({
        fileUrl: fileUrl,
    })
    const [addLibraryFun] = useAddLibraryMutation()
    const [isUpload,setIsUpload] = useState(false)
    const {data:maxFilesData,isSuccess:maxFilesSuccess} = useGetMaxFilesQuery()




    // 定义视频对象的状态
    const [video, setVideo] = useState(null);
    // 定义播放状态
    const [isPlaying, setIsPlaying] = useState(false);

    // 处理视频加载完成的函数
    const onLoad = () => {
        console.log('视频加载完成');
    };

    // 处理视频播放完成的函数
    const onPlaybackStatusUpdate = (status) => {
        if (status.didJustFinish) {
            console.log('视频播放完成');
            setIsPlaying(false);
        }
    };

    // 播放或暂停视频的函数
    const handlePlay = async (item,index) => {
        // if (video) {
        //     if (isPlaying) {
        //         await video.pauseAsync();
        //     } else {
        //         await video.playAsync();
        //     }
        //     setIsPlaying(!isPlaying);
        // }
        router.push('/aiFeeding/playVideo?url='+item.url)
    };

    useEffect(() => {
        if(p.val) {
            // setTypeId('')
            // handleProduct({
            //     id: '',title: '全部'
            // })
            handleTabClickTab(p.val,p.groupIndex)
        }
    }, [p]);

    useEffect(() => {
        if(labelData){
            let list = labelData?.result?.records || []
            let newList = [
                {
                    title: '全部标签',
                    id: null,
                },{
                    title: '无标签',
                    id: 0,
                }
            ]
            list?.map((item, index) => {
                newList.push({
                    ...item,
                    title: item.name
                })
            })
            setLabelList(newList)
        }
        if(libraryData){
            let list = libraryData?.result?.records || []
            // let newList = list?.map((item, index) => {
            //     return {
            //         ...item,
            //         isSelected: false
            //     }
            // })
            setLibraryList(list)

            console.log(libraryList,'libraryList===');
        }
        if(ossInfo&&isUpload){
            takeAddLibrary(ossInfo)
        }

        if(maxFilesData){
            if(maxFilesData?.code === 200){
                let strArr = maxFilesData?.result?.split('/')
                let str = strArr[0] + 'M/' + strArr[1] + 'M'
                setMaxFiles(str)
            }
        }

    }, [labelData,labelSuccess,libraryData,librarySuccess,ossInfo,maxFilesData,maxFilesSuccess]);

    function takeAddLibrary(ossInfo) {
        setIsUpload(false)
        addLibraryFun({
            fileName: ossInfo.fileName,
            fileSourceType: 1,
            fileType: ossInfo.fileType,//1图片资料 2视频资料 3音频资料 4文件资料
            thirdPartyId: id,
            url: ossInfo.fileUrl,
            labelId: labelItem.id,
        }).then(res => {
            console.log(res);
        })
    }

    function handleTabClickTab(val,index) {
        console.log(val,index);
        setLibraryList([])
        setLabelItem(val)
        setLabelIndex(index)
        let p = {...libraryParams,labelId: val.id}
        if(val.id === null){
            delete p.labelId
        }
        setLibraryParams(p)
        // libraryRefetch()
    }

    function handleSelectAll() {
        let newList = JSON.parse(JSON.stringify(libraryList))
        newList.map((item, index) => {
            item.isSelected = true
        })
        setLibraryList(newList)
    }



    const handleSelect = useCallback((item, index) => {
        // let newList = [...libraryList]
        let newList = JSON.parse(JSON.stringify(libraryList))
        newList[index].isSelected = !newList[index].isSelected
        setLibraryList(newList)

        let newSelectData = newList?.filter(item => item.isSelected)
        dispatch(set_selectFileList(newSelectData))
    },[libraryList])

    // const handlePlay = (item, index) => {
    //
    // }
    const handleClick = (item) => {
        setSelectFile(item)
        setDetailIndex(0)
        setShowDetail(true)
        setDetail(item)

        getDocPartsFun({
            id: item.id,
        }).then(res => {
            if (res.data.code === 200) {
                let data = res.data.result || []
                setDetailList(data)
            }
        })
    }

    function changeDetailText(val) {
        let list = JSON.parse(JSON.stringify(detailList))
        list[detailIndex].partText = val
        setDetailList(list)
    }

    function addDetailIndex() {
        setDetailIndex(detailIndex+1)
    }

    function subDetailIndex() {
        setDetailIndex(detailIndex-1)
    }

    function handleToDeleteFile() {
        deleteFileFun({
            id:selectFile.id,
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                dispatch(set_selectFileList([]))
                setShowDetail(false)
                Toast.info('删除成功')
            }
        })
    }

    function handleUseAi() {
        libraryAiFun({
            id:selectFile.id,
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                Toast.info(res.data.result)
            }
        })
    }

    function handleSaveKeyword() {
        let arr = []
        detailList.map((item, index) => {
            let metaData = {}
            if(item.metaData) {
                metaData = JSON.parse(item.metaData)
            }
            arr.push({
                text: item.partText,
                start: metaData?.startTime || 0,
                end: metaData?.endTime || 0,
            })
        })
        saveKeywordFun({
            id:selectFile.id,
            keyword: JSON.stringify(arr),
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                Toast.info('保存成功')
            }
        })
    }

    async function uploadFile() {
        let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

        if (permissionResult.granted === false) {
            alert('Permission to access gallery is required!');
            return;
        }
        let pickerResult = await ImagePicker.launchImageLibraryAsync({
            // mediaTypes: ImagePicker.MediaTypeOptions.Videos,
            // allowsMultipleSelection: true, //可以在相册中选择多个图片或视频
            mediaTypes: ImagePicker.MediaTypeOptions.All, // 选择图片或视频都可以
            allowsEditing: true, // 可选，允许用户编辑所选图片或视频。
            // aspect: [4, 3], // 可选，设置选择的图片或视频的宽高比。
            quality: 1, // 可选，设置图片或视频的质量。0到1之间。1表示最高质量。
        });
        console.log(pickerResult,'pickerResult===');
        if (!pickerResult.canceled) {
            // const file = pickerResult.assets[0];
            // console.log('File name:', file.fileName); // 获取文件名称
            // console.log('File URI:', file.uri); // 获取文件路径
            // console.log('File size:', file.fileSize); // 获取文件大小
            // console.log('File type:', file.type); // 获取文件类型
            // await handleUpload(pickerResult?.assets[0]?.uri); // 处理上传逻辑
            setFileUrl(pickerResult?.assets[0]?.uri)
            setIsUpload(true)
            ossRefetch()
        }
    }

    function handleUpload(url) {
        ossAccessInfoFun().then(res => {
            console.log(res);
            if(res.data.code === 200) {

            }
        })
    }

    function goTabList() {
        router.push('/aiFeeding/tapList')
        dispatch(set_pageRouterParams({
            pathname: `/aiFeeding/tapList`,
            pageName: 'aiFeeding/tapList',
        }))
    }

    return (
        <>
            <View style={{paddingHorizontal: 16}}>
                <FormTitle title='空间容量' isLeftIcon right={
                    <TouchableOpacity onPress={() => router.push('/aiFeeding/dilatation')}>
                        <Text style={{color: '#2856FF'}}>扩容</Text>
                    </TouchableOpacity>}/>
                <FcSlider value={capacity} thumbTintColor='transparent' thumbImage={''} disabled min={0} max={500} onFcSlider={setCapacity} >
                    <Text style={styles.feed}>{maxFiles}</Text>
                </FcSlider>
                <FcBtnScrollTab style={{marginLeft: -8,marginTop: 16}} tabList={labelList} tabIndex={labelIndex} styType='sty2' onTabClick={handleTabClickTab} onClickMenuMore={() => goTabList()}/>
                <FormTitle title='上传视频/图片投喂' isLeftIcon  right={
                    <TouchableOpacity onPress={() => handleSelectAll()}>
                        <Text style={{color: '#2856FF'}}>全选</Text>
                    </TouchableOpacity>}/>
            </View>
            <Flex wrap='wrap'  style={{paddingHorizontal: 12}}>
                <TouchableOpacity style={styles.item_wrap} onPress={()=>uploadFile()}>
                    <View style={[styles.item]}>
                        <Text style={{fontFamily: 'FcIconFont',fontSize: 30,color: 'rgba(0,0,0,1)'}}>&#xe643;</Text>
                        <Text style={{fontSize: 14,color: 'rgba(0, 0, 0, 0.3)',lineHeight: 22,paddingTop: 4}}>点击上传</Text>
                    </View>
                </TouchableOpacity>
                {libraryList?.map((item, index) => (
                    <View style={styles.item_wrap} key={index}>
                        <FcFileItem item={item} selectIcon onClickSelect={()=>handleSelect(item,index)} onClickPlay={()=>handlePlay(item,index)} onClick={()=>handleClick(item)}/>
                    </View>
                ))}

            </Flex>

            {/*<Video*/}
            {/*    ref={(ref) => setVideo(ref)}*/}
            {/*    style={{width: '100%',height: 200,backgroundColor: 'rgba(0,0,0,1)'}}*/}
            {/*    source={{*/}
            {/*        uri: 'https://fcaidata.oss-cn-shenzhen.aliyuncs.com/app/1005/17414436090486c4e3e7b.mp4',*/}
            {/*    }}*/}
            {/*    useNativeControls*/}
            {/*    resizeMode="cover"*/}
            {/*    onLoad={onLoad}*/}
            {/*    onPlaybackStatusUpdate={onPlaybackStatusUpdate}*/}
            {/*/>*/}

            <FcModal
                isOpen={showDetail}
                titleBottomBorderWidth={0}
                onFcModalClose={() => setShowDetail(false)}
                titleText={'详情'}
                bottom={
                    <View style={styles.bottom_btn}>
                        <FcButton
                            onClick={() => handleSaveKeyword()}
                            type='BjJB'
                            colors={['#6989FF', '#C65EFD']}
                            style={{width: '100%', height: 40, justifyContent: 'center'}}
                            itemStyle={{borderRadius: 8, fontSize: 15}}
                            textName='保存'/>
                    </View>
                }
            >
                <View style={styles.detail_wrap}>


                    <FcTextInput multiline text={detailList[detailIndex]?.partText}
                                 placeholder='请输入图片描述或者让AI分析'
                                 onChangeText={(val) => changeDetailText(val)}
                                 height={494}
                                 inputStyle={{paddingTop: 206}}
                                 closeBtnStyle={{top: 202}}
                                 positionEle={
                                     <>
                                         <View style={styles.ai_btn}>
                                             <FcButton
                                                 onClick={() => handleUseAi()}
                                                 type='BjJB'
                                                 colors={['#6989FF', '#C65EFD']}
                                                 style={{width:69, height: 28}}
                                                 itemStyle={{borderRadius: 8, fontSize: 12}}
                                                 textName='AI分析'
                                                 disable={!detailList[detailIndex]?.partText}
                                                 btnLeftEle={
                                                     <Text style={{ fontFamily: 'FcIconFont',fontSize: 16,color: 'white'}}>&#xe63d;</Text>
                                                 }
                                             />
                                         </View>

                                         <View style={styles.file}>
                                             <FcFileItem style={{margin: 0,borderRadius: 0}} item={selectFile} onClickPlay={()=>handlePlay(selectFile,0)} >
                                                 <TouchableOpacity style={styles.delete_btn} onPress={() => setIsDelete(true)}>
                                                     <Text style={{ fontFamily: 'FcIconFont',fontSize: 20,color: 'white'}}>&#xe61d;</Text>
                                                 </TouchableOpacity>

                                             </FcFileItem>
                                         </View>

                                         <View style={styles.tab_wrap}>
                                             <FileTabBtn btnStyles={{backgroundColor:'white'}} index={detailIndex} len={detailList.length} onClickAdd={addDetailIndex} onClickSub={subDetailIndex}></FileTabBtn>
                                         </View>
                                     </>
                                 }
                    />
                </View>
            </FcModal>

            <FcModal
                isOpen={isDelete}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsDelete(false)}
                style={styles.modal_default}
                titleText={'确认要删除吗？'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsDelete(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => handleToDeleteFile(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前标签将被删除哦~</Text>
            </FcModal>
        </>
    )
}

export default fileFeed

const styles = StyleSheet.create({
    feed: {
        fontSize: 12,
        paddingTop: 8,
        color: 'rgba(0,0,0,0.9)'
    },
    item_wrap: {
        width: '50%',
        height: 116,
    },

    item: {
        flex: 1,
        borderRadius: 8,
        overflow: "hidden",
        position: "relative",
        margin: 4,
        backgroundColor: '#F1F2F4',
        borderWidth: 1,
        borderColor: 'rgba(0,0,0,0.1)',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
    },

    ai_btn: {
        width: 69,
        height: 28,
        position: "absolute",
        right: 8,
        bottom: 8
    },

    tab_wrap: {
        position: "absolute",
        left: 8,
        bottom: 8,
    },

    detail_wrap: {
        marginHorizontal: 16,
        backgroundColor: '#F1F2F4',
        borderRadius: 8,
        overflow: "hidden",
        marginBottom: 50
    },

    file: {
        width: '100%',
        height: 194,
        // marginBottom: 12,
        position: "absolute",
        left: 0,
        top: 0
    },

    delete_btn: {
        width: 28,
        height: 28,
        borderRadius: 8,
        position: "absolute",
        top: 10,
        right: 10,
        zIndex: 100,
        backgroundColor: 'rgba(0,0,0,0.5)',
        display: 'flex',
        justifyContent: "center",
        alignItems: 'center'
    },

    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },

    bottom_btn: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: 16,
        height: 56,
        justifyContent: "center",
        backgroundColor: 'white',
    },
})